package ldh.im.monitor.service;

import javafx.application.Platform;
import ldh.im.ImConfig;
import ldh.im.dto.business.user.LoginResp;
import ldh.im.dto.business.user.ReConnection;
import ldh.im.fxbase.util.DialogUtil;
import ldh.im.fxbase.util.FxThreadUtil;
import ldh.rpc.RpcConfig;
import ldh.rpc.TerminalType;
import ldh.rpc.cache.CacheService;
import ldh.rpc.client.DefaultCommunicateService;
import ldh.rpc.client.RpcClientConnection;
import ldh.rpc.dto.RpcData;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class ImCommunicateService extends DefaultCommunicateService {

    private RpcConfig rpcConfig = null;

    public ImCommunicateService(RpcConfig rpcConfig) {
        super(rpcConfig);
        this.rpcConfig = rpcConfig;
    }

    @Override
    public void reconnection(RpcClientConnection rpcClientConnection) throws InterruptedException, ExecutionException, TimeoutException {
        CacheService cacheService = rpcConfig.getCacheService();
        Object userId = cacheService.getCache(ImConfig.LOGIN_USER_ID);
        if (userId != null) {
            ReConnection reConnection = new ReConnection();
            Object tenantCode = cacheService.getCache(ImConfig.TENANT_ID);
            Object authToken = cacheService.getCache(ImConfig.AUTH_TOKEN);
            if (tenantCode != null && authToken != null) {
                reConnection.setTerminalType(TerminalType.pc);
                reConnection.setTenantCode(tenantCode.toString());
                reConnection.setAuthToken(authToken.toString());
                RpcData<ReConnection> rpcData = new RpcData<>();
                rpcData.setData(reConnection);
                rpcData.setPath("reconnection");
                rpcData.setVersion(1);
                rpcData.setStatus(0);
                rpcData.setLocalSeq("2");
                LoginResp loginResp = rpcClientConnection.write(rpcData, 30);
                cacheService.setCache(ImConfig.LOGIN_USER_ID, loginResp.getUserId(), null);
                cacheService.setCache(ImConfig.TENANT_ID, loginResp.getTenantCode(), null);
                cacheService.setCache(ImConfig.AUTH_TOKEN, loginResp.getAuthToken(), null);
                cacheService.setCache(ImConfig.AUTH_CODE, loginResp.getAuthCode(), null);
            } else {
                FxThreadUtil.runLater(()->{
                    DialogUtil.alert("用户离线", "用户已经离线，请重新登录");
                });
            }
        }
    }
}
